perf(uniq): Improve performance of uniq
function
#40
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What have been changed
Previous code used
for ... of ...
statement to check whether an item included in result array. I've changed it to return unique values withSet
.Improvement
for ... of ...
isO(N)
.Array.prototype.includes
does linear search, so it isO(N)
considering the worst case scenario. So the code before had time complexity ofO(N^2)
.new Set()
isO(N)
,Array.from()
is alsoO(N)
, so total time complexity becomesO(N)
.100,000
25,000
75,000
existing code
: 542.303459 msupdated code
: 3.931583 msPossible drawbacks
Array.prototype.includes
have out with ES7, on the other handSet
have done with ES6. So updated method also supports older version without polyfill.Set
also keeps its insertion order.uniq
function createsSet
object every time when function is called. There is chance that slight increase in memory usage. But I guess it does not make huge difference from makingresult
array every time.Added test cases
I've added test cases related to
uniq
function updates which assures its original functions.Considering performance is primary factor of
es-toolkit
lib, this pr should be fair enough.Let me know if other drawback does this pr have.